import { createRandomMapPoint, drawLine, drawRect, getRandomInit, searchRoad } from './utils.js';

const canvas = document.getElementById('canvas');

canvas.width = 800;
canvas.height = 800;

const ctx = canvas.getContext('2d');

const MAP = {
  rows: 80,
  cols: 80,
  arr: [],
};
let cellSize = Math.floor(canvas.width / MAP.rows);
console.log('cellSize:', cellSize);

let startPoint = { x: 2, y: 2 }, // 起点
  endPoint = { x: 20, y: 20 }; // 终点

// x方向和y方向的移动增量
let nextPoint = { x: 0, y: 0 }, // 移动的下一格
  nextPointIndex = 0;

let roadPoints = [];

window.onload = function () {
  initializeGrid();
  initPoint();
};

const initializeGrid = () => {
  MAP.arr = [];
  roadPoints = [];
  // 生成随机地图
  for (let i = 0; i < canvas.width; i += cellSize) {
    let column = [];
    for (let j = 0; j < canvas.height; j += cellSize) {
      // 1 为障碍物
      column.push(Math.random() > 0.9 ? 1 : 0);
    }
    MAP.arr.push(column);
  }
  console.log('MAP.arr:', MAP.arr);
};

const getRoad = () => {
  roadPoints = [];
  nextPoint = { x: 0, y: 0 };
  let arr = searchRoad(startPoint.x, startPoint.y, endPoint.x, endPoint.y, MAP);
  if (arr.length === 0) {
    console.log('未找到路径');
    roadPoints = [];
    return;
  }
  if (arr.length >= 1) {
    roadPoints = arr;
    nextPoint = roadPoints[0];
    nextPointIndex = 0;
  }
};

const initPoint = () => {
  // 生成随机起始结束点
  startPoint = createRandomMapPoint(MAP);
  endPoint = createRandomMapPoint(MAP);
};

document.getElementById('createMap').addEventListener('click', () => {
  initializeGrid();
});
document.getElementById('exportMap').addEventListener('click', () => {
  console.log('地图数据');
  console.log(JSON.stringify(MAP.arr));
  console.log('坐标数据');
  console.log(`startPoint:${startPoint} endPoint:${endPoint}`);
});
document.getElementById('createPoint').addEventListener('click', () => {
  initPoint();
  roadPoints = [];
  getRoad();
});
document.getElementById('createEndPoint').addEventListener('click', () => {
  endPoint = createRandomMapPoint(MAP);
  roadPoints = [];
  getRoad();
});
document.getElementById('getRoad').addEventListener('click', () => {
  getRoad();
});

canvas.addEventListener('click', (e) => {
  let { left, top } = canvas.getBoundingClientRect();
  let x = Math.floor((e.clientX - left) / cellSize);
  let y = Math.floor((e.clientY - top) / cellSize);
  console.log(`点击的坐标为：x: ${x}  y: ${y}`);
  while (MAP.arr[x][y] === 1) {
    x += Math.random() > 0.5 ? 1 : -1;
  }
  endPoint = { x, y };
  getRoad();
});

const draw = () => {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  // 画地图
  for (let i = 0; i < MAP.arr.length; i++) {
    let column = MAP.arr[i];
    for (let j = 0; j < column.length; j++) {
      drawRect(ctx, i * cellSize, j * cellSize, cellSize, cellSize, column[j] === 1 ? 'blue' : 'gray');
    }
  }

  if (roadPoints.length > 0) {
    // 画寻路的路径
    for (let i = 0; i < roadPoints.length; i++) {
      const element = roadPoints[i];
      drawRect(ctx, element.x * cellSize, element.y * cellSize, cellSize, cellSize, 'green');
    }

    // 移动起点到终点
    if (startPoint.x !== endPoint.x || startPoint.y !== endPoint.y) {
      // 当前要移动的下一个目标点不是终点的话
      if (nextPointIndex <= roadPoints.length) {
        // 移动逻辑
        if (startPoint.x === nextPoint.x && startPoint.y === nextPoint.y) {
          nextPoint = roadPoints[nextPointIndex++];
        } else {
          if (startPoint.x === nextPoint.x) {
            // 判断是否在同一垂直线上，只能上下移动
            startPoint.y += nextPoint.y - startPoint.y;
          } else if (startPoint.y === nextPoint.y) {
            // 判断是否在同一水平线上，只能左右移动
            startPoint.x += nextPoint.x - startPoint.x;
          } else {
            // 斜向将两个方向都进行移动
            startPoint.y += nextPoint.y - startPoint.y;
            startPoint.x += nextPoint.x - startPoint.x;
          }
        }
      }
    }
  }

  // 画起始点和终点
  drawRect(ctx, endPoint.x * cellSize, endPoint.y * cellSize, cellSize, cellSize, 'red');
  drawRect(ctx, startPoint.x * cellSize, startPoint.y * cellSize, cellSize, cellSize, 'yellow');

  drawLine(ctx, (nextPoint.x + 0.5) * cellSize, 0, (nextPoint.x + 0.5) * cellSize, canvas.height);
  drawLine(ctx, 0, (nextPoint.y + 0.5) * cellSize, canvas.width, (nextPoint.y + 0.5) * cellSize);

  requestAnimationFrame(draw);
};

draw();
